package com.app.micaihu.view.login;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.app.micaihu.R;
import com.app.micaihu.app.AppApplication;
import com.app.micaihu.base.BaseOldActivity;
import com.app.micaihu.base.bean.DataBean;
import com.app.micaihu.bean.infor.UserInfor;
import com.app.micaihu.configure.Config;
import com.app.micaihu.configure.TypeConstant;
import com.app.micaihu.configure.URIContant;
import com.app.micaihu.custom.components.ParamMap;
import com.app.micaihu.manager.UserInforManager;
import com.app.micaihu.utils.DialogUtils;
import com.app.micaihu.utils.HttpUtils;
import com.app.micaihu.listener.HttpListener;
import com.app.utils.util.ToastUtils;
import com.google.gson.reflect.TypeToken;

import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Guo on 2016/7/14.
 * 更换手机号和注册的 接受验证码的页面
 */
public class PhoneResgiterCodeActivity extends BaseOldActivity implements View.OnClickListener {
    /**
     * 提示的手机号
     */
    private TextView tvPhoneNum;
    /**
     * 验证码
     */
    private EditText etPhoneCode;
    /**
     * 倒计时
     */
    private TextView tvCountdown;
    /**
     * 下一步
     */
    private TextView tvNext;
    /**
     * 上个页面传递过来的意图
     */
    private Intent intent;

    /**
     * 是否发送过验证码
     */
    private static boolean isSendcode;
    private Timer mTimer;//timer
    private static int time;//倒计时
    private static TimerTask mTimerTask;//倒计时任务
    private static boolean mIsSendcode;//是否发送验证码


    //操作倒计时的操作handler
    private Handler mHandler = new Handler() {

        public void handleMessage(android.os.Message msg) {
            if (time <= 0 && tvCountdown != null) {
                tvCountdown.setText("重新发送");
                tvCountdown.setClickable(true);
                return;
            }
            if (tvCountdown != null) {
                tvCountdown.setText(time + "s");
            }
        }
    };
    /**
     * 当前手机号的文本
     */
    private String mPhoneNum;
    /**
     * 发送成功/失败的提示语
     */
    private TextView tvPropmt;
    /**
     * 发送来的验证码文本
     */
    private String code;
    /**
     * 动作类型
     */
    private String actionType;
    private static String typeLoa;//记录上一次进入的页面动作


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addContentView(R.layout.activity_phonecode);
        intent = getIntent();
        initView();
        initListener();

        //设定倒计时
        setTimer();
    }

    private void initView() {

        tvPhoneNum = (TextView) findViewById(R.id.tv_phonenum);
        tvPropmt = (TextView) findViewById(R.id.tv_propmt);
        etPhoneCode = (EditText) findViewById(R.id.et_phonecode);
        tvCountdown = (TextView) findViewById(R.id.tv_countdown);
        tvNext = (TextView) findViewById(R.id.tv_next);

        tvNext.setEnabled(false);

        actionType = intent.getStringExtra(TypeConstant.ACTION_TYPE);
        if (TextUtils.isEmpty(typeLoa)) {//记录此次是什么动作
            typeLoa = actionType;
        }
        if (tvNext == null && tvPhoneNum == null) return;
        if (intent == null) {
            tvPhoneNum.setVisibility(View.INVISIBLE);
        } else {
            tvPhoneNum.setVisibility(View.VISIBLE);

            if (TextUtils.equals(actionType, TypeConstant.CHANGEPHONE_ACTION)) {
                setTitle("更换手机号");
                tvNext.setText("确认更换");
                String mNewPhoneNum = intent.getStringExtra("newphone");
                mPhoneNum = intent.getStringExtra("phone");
                tvPhoneNum.setText(mNewPhoneNum);
            } else if (TextUtils.equals(actionType, TypeConstant.REGISTER_ACTION)) {
                setTitle("注册");
                tvNext.setText("下一步");
                mPhoneNum = intent.getStringExtra("phone");
                tvPhoneNum.setText(mPhoneNum);
            }
        }
    }

    private void initListener() {

        tvCountdown.setOnClickListener(this);

        tvCountdown.setClickable(false);

        tvNext.setOnClickListener(this);
        etPhoneCode.addTextChangedListener(tw);
    }

    /**
     * edittext的监听
     */
    TextWatcher tw = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (etPhoneCode == null || tvNext == null) return;
            if (etPhoneCode.getText().toString().trim().length() >= 4) {
                tvNext.setEnabled(true);
            } else {
                tvNext.setEnabled(false);
            }
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    };


    private void setTimer() {
        /**
         * 如果当前有任务进行则 停止任务从新建立一个任务
         * 如果没有任务进行则判断之前是否执行过任务，如果有则不建立任务
         * 如果没有则建立新的任务
         */

        if (!TextUtils.isEmpty(actionType) && !TextUtils.equals(actionType, typeLoa)) {//证明不是上一次与这一次 进来的页面不同
            sendCode();
            typeLoa = actionType;
        } else {
            if (time > 0) {
                tvCountdown.setText(time + "s");
                if (mTimerTask != null) {
                    mTimerTask.cancel();
                }
                if (mTimer == null) {
                    mTimer = new Timer();
                }
                mTimerTask = new TimerTask() {

                    @Override
                    public void run() {
                        time--;
                        if (mHandler != null) {
                            mHandler.sendEmptyMessage(0);
                        }
                        if (time <= 0) {
                            cancel();
                        }

                    }
                };
                mTimer.schedule(mTimerTask, 1000, 1000);
            } else if (!mIsSendcode) {
                sendCode();
            } else {
                tvCountdown.setClickable(true);
                tvCountdown.setText("重新发送");

            }

        }


    }

    /**
     * 发送验证码
     */
    private void sendCode() {
       /* if (time > 0) {
            return;
        }*/
        tvCountdown.setClickable(false);
        if (mTimerTask != null) {
            mTimerTask.cancel();
        }
        if (mTimer == null) {
            mTimer = new Timer();
        }
        time = 60;
        tvCountdown.setText(time + "s");

        mTimerTask = new TimerTask() {

            @Override
            public void run() {
                time--;
                if (mHandler != null) {
                    mHandler.sendEmptyMessage(0);
                }
                if (time <= 0) {
                    cancel();
                }
            }
        };
        mTimer.schedule(mTimerTask, 1000, 1000);

        //发送网络请求
        //Map<String, String> paramSend = new HashMap<>();
        ParamMap paramSend = new ParamMap();
        getParamCode(paramSend, actionType);

        if (paramSend.size() <= 0) {
            ToastUtils.makeText("程序异常,请重新打开本页");
            return;
        }

        //已发送验证码
        //isSendcode = true;

        addPostRequest(URIContant.SEND_CODE, new TypeToken<DataBean>() {
        }.getType(), paramSend, new HttpListener<DataBean>() {
            @Override
            public void onStart() {
                super.onStart();
                mIsSendcode = true;
                DialogUtils.getInstance().showProgressDialog(PhoneResgiterCodeActivity.this, "正在发送");
            }

            @Override
            public void onError(VolleyError error) {
                tvPropmt.setText("发送失败");
                tvPhoneNum.setVisibility(View.GONE);
                DialogUtils.getInstance().dismissProgressDialog();
                ToastUtils.makeText(AppApplication.getInstance().getResources().getString(R.string.neterror));
            }

            @Override
            public void onSuccess(DataBean response) {
                //mTimer.schedule(mTimerTask, 1000, 1000);
                //isSendcode = true;
                //如果发送失败则显示提示信息
                if (!response.noError()) {
                    if (tvPropmt != null) {
                        tvPropmt.setText(response.getMsg());
                    }
                    if (mTimerTask != null) {
                        mTimerTask.cancel();
                    }
                    if (tvCountdown != null) {
                        tvCountdown.setText("重新发送");
                    }
                    time = 0;
                } else {
                    //成功
                    tvPropmt.setText("我们已经发送了验证码到您的手机");
                    tvPhoneNum.setVisibility(View.VISIBLE);

                }
                DialogUtils.getInstance().dismissProgressDialog();
            }
        });


    }


    @Override
    public void onClick(View v) {
        if (v == null)
            return;
        switch (v.getId()) {
            case R.id.tv_countdown:
                sendCode();// 发送验证码
                break;
            case R.id.tv_next://下一步
                next();
                break;

            default:
                break;
        }

    }

    /**
     * 跳转下一步
     */
    private void next() {

        if (etPhoneCode == null || TextUtils.isEmpty(mPhoneNum)) {
            ToastUtils.showText("程序异常,请重新注册");
            return;
        }
        code = etPhoneCode.getText().toString().trim();
        if (TextUtils.isEmpty(code)) {
            ToastUtils.makeText("请输入验证码");
            return;
        }

        //访问网络

//        Map<String, String> params = new HashMap<>();
        if (request_state) return;
        ParamMap params = new ParamMap();
        String url = getParamNext(params, actionType);
        if (params.size() <= 0) {
            ToastUtils.makeText("程序异常,请重新打开本页");
            return;
        }

        addPostRequest(url, new TypeToken<DataBean>() {
        }.getType(), params, new HttpListener<DataBean>() {
            @Override
            public void onStart() {
                super.onStart();
                request_state = true;
                DialogUtils.getInstance().showProgressDialog(PhoneResgiterCodeActivity.this, "正在跳转");
            }

            @Override
            public void onError(VolleyError error) {
                request_state = false;
                ToastUtils.makeText(AppApplication.getInstance().getResources().getString(R.string.neterror));
                DialogUtils.getInstance().dismissProgressDialog();
            }

            @Override
            public void onSuccess(DataBean response) {

                if (response.noError()) {
                    successDo(response, actionType);
                } else {
                    DialogUtils.getInstance().dismissProgressDialog();
                    ToastUtils.makeText(response.getMsg());
                }
                request_state = false;
            }
        });

    }


    /**
     * 下一步成功后,根据actionType来决定后续操作
     *
     * @param response
     * @param actionType
     */
    private void successDo(DataBean response, String actionType) {
        if (TextUtils.isEmpty(actionType)) {
            ToastUtils.makeText("程序异常,请重新打开本页");
            return;
        }
        switch (actionType) {
            case TypeConstant.CHANGEPHONE_ACTION://更改手机号
                DialogUtils.getInstance().dismissProgressDialog();

                ToastUtils.makeText("更换手机号成功");
                String msg = response.getMsg();
                UserInfor userInfor = UserInforManager.getInstance().getUserInfor();
                //将数据存到userinfor中
                userInfor.setMobile(intent.getStringExtra("newphone"));
                //保存到本地中
                UserInforManager.getInstance().saveUserInfor(userInfor);
                DialogUtils.getInstance().dismissProgressDialog();
                setResult(Activity.RESULT_OK);
                onBackPressed();
                break;
            case TypeConstant.REGISTER_ACTION://注册
//                Intent intent = new Intent(PhoneResgiterCodeActivity.this, PhoneRegisterOptionActivity.class);
//                DialogUtils.getInstance().dismissProgressDialog();
//                intent.putExtra("phone", mPhoneNum);
//                startActivityForResult(intent, REQUESTCODE_1);
                break;
          /*  case TypeConstant.BINDPHONE_ACTION://绑定手机号

                break;

            case TypeConstant.RESETPWD_ACTION://重设密码

                break;*/
        }

    }


    /**
     * 获取下一步的 参数
     *
     * @param params
     * @param actionType
     * @return
     */
    private String getParamNext(ParamMap params, String actionType) {

        params.clear();
        String url = "";
        switch (actionType) {
            case TypeConstant.CHANGEPHONE_ACTION://更改手机号
                String newphone = intent.getStringExtra("newphone");
                params.put("mobile", newphone);
                params.put("captcha", code);
                params.put("uid", UserInforManager.getInstance().getUserInfor().getUid());
                url = URIContant.CHANGE_PHONE;
                break;

            case TypeConstant.REGISTER_ACTION://注册
                params.put("mobile", mPhoneNum);
                params.put("captcha", code);
                url = URIContant.CHECK_CODE;
                break;

        }

        HttpUtils.ParmsMapMD5(params);

        return url;
    }


    /**
     * 获取发送验证码的参数
     *
     * @param params
     * @param actionType
     * @return
     */
    private void getParamCode(ParamMap params, String actionType) {

        params.clear();
        switch (actionType) {
            case TypeConstant.CHANGEPHONE_ACTION://更改手机号
                params.put("mobile", mPhoneNum);
                params.put("type", TypeConstant.CHANGEPHONE_CODE);
                params.put("newMobile", intent.getStringExtra("newphone"));
                params.put("uid", UserInforManager.getInstance().getUserInfor().getUid());
                break;

            case TypeConstant.REGISTER_ACTION://注册
                params.put("mobile", mPhoneNum);
                params.put("type", TypeConstant.REGISTER_CODE);
                params.put("newMobile", "");
                params.put("uid", "");
                break;
        }

        //加密
        HttpUtils.ParmsMapMD5(params);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Config.ResultCode.REQUESTCODE_1 && resultCode == RESULT_OK) {
            setResult(resultCode);
            onBackPressed();
        }

    }


    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        mHandler = null;
    }
}
